package com.atguigu.day06;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;

public class Example01 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<String> result = env.socketTextStream("192.168.1.102", 9999)
                .map(x -> {
                    String[] arr = x.split(" ");
                    return Tuple2.of(arr[0], Long.parseLong(arr[1]) * 1000L);
                })
                .returns(Types.TUPLE(Types.STRING,Types.LONG))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Tuple2<String, Long>>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                                .withTimestampAssigner(new SerializableTimestampAssigner<Tuple2<String, Long>>() {
                                    @Override
                                    public long extractTimestamp(Tuple2<String, Long> element, long recordTimestamp) {
                                        return element.f1;
                                    }
                                })
                )
                .keyBy(x -> true)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .sideOutputLateData(new OutputTag<Tuple2<String, Long>>("late_Event"){})
                .allowedLateness(Time.seconds(5))
                .process(new ProcessWindowFunction<Tuple2<String, Long>, String, Boolean, TimeWindow>() {

                    @Override
                    public void process(Boolean aBoolean, Context context, Iterable<Tuple2<String, Long>> elements, Collector<String> out) throws Exception {
                        //  context.windowState().getState              窗口状态
                        //   getRuntimeContext().getState().getState    键控状态
                        ValueState<Boolean> flag = context.windowState().getState(new ValueStateDescriptor<Boolean>(
                                "first_flag", Boolean.class)
                        );
                        if (flag.value() == null) {
                            out.collect("正常  个数：" + elements.spliterator().getExactSizeIfKnown());
                            flag.update(true);
                        } else {
                            out.collect("迟到  个数：" + elements.spliterator().getExactSizeIfKnown());
                        }
                    }
                });
        result.print("数据：");
        result.getSideOutput(new OutputTag<Tuple2<String,Long>>("late_Event"){}).print("彻底完球");

        env.execute();
    }
}
